package com.module.interceptor;

import java.io.PrintWriter;
import java.util.LinkedHashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * 控制层增强器
 * @author chengluqiang
 * @since 2019-02-27 23:33
 */
@ControllerAdvice
public class ExceptionInterceper{
	
	/**
	 * 全局异常拦截器
	 * @author chenluqiang
	 * @date 2019年3月12日 上午11:37:28 
	 * @param e
	 * @return
	 * @throws Exception
	 */
	@ExceptionHandler(value=Exception.class)
	public ModelAndView defaultErrorHandler(HttpServletRequest request,HttpServletResponse response, Exception e)throws Exception
   {
	  ModelAndView view = new ModelAndView();
	  Map<String,Object> result = new LinkedHashMap<>();
	  result.put("code","500");
	  result.put("status","ERROR");
	  result.put("msg",e.getMessage());
	  result.put("url",request.getRequestURL());
	  //创建json转换的类
		ObjectMapper mapper = new ObjectMapper();
		PrintWriter writer = null;
		try {
			String jsonString = mapper.writeValueAsString(result);
			// 避免乱码
			response.setCharacterEncoding("UTF-8");
			// 设置ContentType
			response.setContentType("application/json; charset=utf-8");
			writer = response.getWriter();
			writer.write(jsonString);
		} catch (Exception e2) {
			e2.printStackTrace();
		}finally {
			writer.close();
		}
      return view;
   }
	
}
